package com.geen.tuoke.utils

import android.app.Activity
import java.util.*

/**
 * @author
 * @date 2018/7/10
 * @desc
 */
class AppManager private constructor() {

    fun removeActivity(activity: Activity) {
        if (activityStack != null) {
            val iterator =
                activityStack!!.iterator()
            while (iterator.hasNext()) {
                val act = iterator.next()
                if (act === activity) {
                    iterator.remove()
                    break
                }
            }
        }
    }

    /**
     * 添加Activity到堆栈
     */
    fun addActivity(activity: Activity?) {
        if (activityStack == null) {
            activityStack = Stack()
        }
        activityStack!!.add(activity)
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    fun currentActivity(): Activity? {
        return activityStack!!.lastElement()
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    fun finishActivity() {
        val activity = activityStack!!.lastElement()
        finishActivity(activity)
    }

    /**
     * 结束指定的Activity
     */
    fun finishActivity(activity: Activity?) {
        var activity = activity
        if (activity != null && activityStack != null && activityStack!!.size > 0) {
            activityStack!!.remove(activity)
            activity.finish()
            activity = null
        }
    }


    /**
     * 结束所有Activity
     */
    fun finishAllActivity() {
        if (activityStack == null || activityStack!!.size == 0) {
            return
        }
        var i = 0
        val size = activityStack!!.size
        while (i < size) {
            if (null != activityStack!![i]) {
                activityStack!![i]!!.finish()
            }
            i++
        }
        activityStack!!.clear()
    }

    companion object {
        private var activityStack: Stack<Activity?>? = null
        private var instance: AppManager? = null

        /**
         * 单一实例
         */
        val appManager: AppManager?
            get() {
                if (instance == null) {
                    synchronized(AppManager::class.java) {
                        if (instance == null) {
                            instance = AppManager()
                        }
                    }
                }
                return instance
            }
    }
}